package life.codelearing.service;

import life.codelearing.bean.DepartmentExample;
import life.codelearing.bean.Employee;
import life.codelearing.bean.EmployeeExample;
import life.codelearing.dao.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;

    /**
     * 获取所有员工列表,并按照序号排序
     *
     * 错误：新增的员工ID值没有正确的排列
     * 原因：左外连接查询会根据主表向从表一个一个的查，导致从表的dept_id等于1的先查出来。
     * @return
     */
    public List<Employee> getAll() {
        EmployeeExample example = new EmployeeExample();
        example.setOrderByClause("emp_id");
        return  employeeMapper.selectByExampleWithDept(example);
    }

    /**
     * 员工保存方法
     * @param employee
     */
    public void saveEmp(Employee employee) {
        employeeMapper.insertSelective(employee);
    }

    /**
     * 检验此empName是否已经存在
     * 使用查询条件，条件为是否能查找到此用户名的记录值
     * 返回值为true，表示没有此用户名，此用户名可用
     * @param empName
     */
    public boolean checkUser(String empName) {
        //构建查询条件
        EmployeeExample employeeExample = new EmployeeExample();
        EmployeeExample.Criteria criteria = employeeExample.createCriteria();
        criteria.andEmpNameEqualTo(empName);
        Long isExist = employeeMapper.countByExample(employeeExample);
        return isExist==0;
    }

    /**
     * 按照id查询employee信息
     *
     * @param id
     * @return
     */
    public Employee getEmp(Integer id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    /**
     * 员工更新方法
     * @param employee
     * @return
     */
    public void updateEmp(Employee employee) {
        employeeMapper.updateByPrimaryKeySelective(employee);
    }

    /**
     * 通过id删除单个员工信息
     * @param id
     */
    public void deleteEmpById(Integer id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    /**
     * 按照多个id批量删除
     * @param ids
     */
    public void deleteBatch(List<Integer> ids) {
        EmployeeExample example = new EmployeeExample();
        EmployeeExample.Criteria criteria = example.createCriteria();
        criteria.andEmpIdIn(ids);
        employeeMapper.deleteByExample(example);

    }
}
